package com.pms.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  单元管理界面接口
 * 1) 因锁设备需要绑定单元编号，所以==》单元创建后不能删除，只能屏蔽app端显示，且每个小区只能创建 250个单元。
 * 2) 因单元不能删除 ==》 添加  清空单元房屋信息 方法
 * </p>
 *
 * @author ASUS_B
 * @since 2017-10-24
 */
@RestController
@RequestMapping("/unitBuildingBase")
@Api(value="小区单元管理界面接口",description = "小区单元管理界面接口")
public class UnitBuildingController extends BaseController {
    @Autowired
    private IUnitBuildingService unitBuildingService;
    @Autowired
    private IEstateAgencyService estateAgencyService;
    @Autowired
    private IUnitHouseService unitHouseService;
    @Autowired
    private IUnitFloorService unitFloorService;
    @Autowired
    private IHouseMasterInfoService houseMasterInfoService;
    @Autowired
    IChargeTemplateService chargeTemplateService;
    @Autowired
    private IEntranceDoorService entranceDoorService;
    @Autowired
    private IOwnerMemberService ownerMemberService;
    @ApiOperation(value = "添加单元")
    @RequestMapping(value = "/addUnit",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="unitName",value="单元名称",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="communityId",value="社区id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="isShowApp",value="app是否显示(1-显示(默认)，2-不显示)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="unitRemarks",value="备注信息",required = false,dataType = "String",paramType="form"),
    })
    public R addUnitBuilding(String unitName,Integer isShowApp,Long communityId,String unitRemarks){
        parameterIsBlank(unitName,"请填写单元名称");
        parameterIsNull(communityId,"社区id不能为空");
        if(null==isShowApp||isShowApp!=2){isShowApp=1;}//默认App显示
        if(StringUtils.isBlank(unitRemarks)){unitRemarks="";}
        int countUnitName = unitBuildingService.selectCount(new EntityWrapper<UnitBuilding>().eq("community_id",communityId).eq("unit_name",unitName.trim()));
        if(countUnitName>0){ return  R.error(400,"单元名称已存在");}
        if(unitName.length()>=50){ return  R.error(400,"单元名称内容过长");}
        if(unitRemarks.length()>=200){ return  R.error(400,"备注信息内容过长");}
        EstateAgency agencyInfo= estateAgencyService.selectById(communityId);
        parameterIsNull(communityId,"该社区信息不存在");
        if(agencyInfo.getAgencyType()!=2){return R.error(400,"社区类型不匹配");  }
        int maxUnitNum = unitBuildingService.getMaxUnitNum(communityId);
        if(maxUnitNum>=250){ return R.error(400,"小区单元数已达上限，无法创建"); }
        UnitBuilding unit = new UnitBuilding();
        unit.setCommunityId(communityId);
        unit.setCommunityNum(agencyInfo.getCommunityNum());
        unit.setIsShowApp(isShowApp);
        unit.setUnitName(unitName.trim());
        unit.setUnitNum(maxUnitNum+1);
        unit.setUnitRemarks(unitRemarks.trim());
        unit.setAgencyId(agencyInfo.getParentId());
        unitBuildingService.insert(unit);
        // 同步清除 查询单元楼层户室的缓存
        unitBuildingService.clearPreKeyCache("unitHouse:selectUnitFloorHouse");
        //自动创建单元门
        EntranceDoor door = new EntranceDoor().setDoorName(unit.getUnitName()+"门").setDoorType(2).setCommunityId(unit.getCommunityId())
                .setAgencyId(unit.getAgencyId()).setCommunityNum(unit.getCommunityNum()).setUnitNum(unit.getUnitNum())
                .setDoorRemarks("").setIsHaveLock(2);
        entranceDoorService.insert(door);
        return R.ok();
    }
    @ApiOperation(value = "查询单元信息")
    @RequestMapping(value = "/readInfo",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="unitId",value="单元id",required = true,dataType = "String",paramType="form"),
    })
    public R readInfo(@RequestParam String unitId) {
        parameterIsBlank(unitId,"单元id不能为空");
        UnitBuilding unitBuilding = unitBuildingService.selectById(unitId);
        return R.ok().put("data",unitBuilding).putDescription(UnitBuilding.class);
    }

    @ApiOperation(value = "分页查询小区下级单元")
    @RequestMapping(value = "/readPage",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageSize",value="请求条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageNum",value="请求页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="communityId",value="社区id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="agencyId",value="物业机构id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="isShowApp",value="app是否显示(1-显示，2-不显示,3-所有(默认))",required = false,dataType = "int",paramType="form"),
    })
    public R readPage(Integer pageSize,Integer pageNum,Long communityId,Integer isShowApp,Long agencyId) {
        parameterIsNull(agencyId,"物业机构id不能为空");
        if(null==pageNum||pageNum<1){pageNum=1;}
        if(null==pageSize||pageSize<1){pageSize=10;}
        Page<UnitBuilding> page = new Page<UnitBuilding>(pageNum,pageSize);
        Wrapper<UnitBuilding> wrapper=  new EntityWrapper<UnitBuilding>();
        if(null!=agencyId){
            wrapper.eq("agency_id",agencyId);
        }
        if(null!=communityId){
            wrapper.eq("community_id",communityId);
        }
        if(null!=isShowApp) {
            if (isShowApp == 2 || isShowApp == 1) {
                wrapper.eq("is_show_app", isShowApp);
            }
        }
        Page<UnitBuilding> returnPage = unitBuildingService.selectPage(page,wrapper);
        return R.ok().put("data",returnPage).putMpPageDescription().putDescription(UnitBuilding.class);
    }

    @ApiOperation(value = "改变单元是否在app端显示")
    @RequestMapping(value = "/changeIsShowApp",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="unitId",value="单元id",required = true,dataType = "long",paramType="form"),
    })
    public R changeIsShowApp(Long unitId) {
        parameterIsNull(unitId,"单元id不能为空");
        UnitBuilding unitBuilding = unitBuildingService.selectById(unitId);
        parameterIsNull(unitBuilding,"没有该单元信息");
        if(null==unitBuilding.getIsShowApp()||1==unitBuilding.getIsShowApp()){
            unitBuilding.setIsShowApp(2);
        }else{
            unitBuilding.setIsShowApp(1);
        }
        unitBuildingService.updateById(unitBuilding);
        return R.ok();
    }

    @ApiOperation(value = "修改单元信息")
    @RequestMapping(value = "/editUnit",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="unitId",value="单元id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="unitName",value="单元名称",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="isShowApp",value="app是否显示(1-显示(默认)，2-不显示)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="unitRemarks",value="备注信息",required = false,dataType = "String",paramType="form"),
    })
    public R editUnitBuilding(Long unitId,String unitName,Integer isShowApp,String unitRemarks ) {
        parameterIsNull(unitId,"单元id不能为空");
        UnitBuilding unitBuilding = unitBuildingService.selectById(unitId);
        parameterIsNull(unitBuilding,"没有该单元信息");
        boolean upTag =false;
        boolean upUnitNameTag =false;
        if(StringUtils.isNotBlank(unitName)){
            if(unitName.length()>=50){return  R.error(400,"单元名称内容过长");}
            if(! unitBuilding.getUnitName().equals(unitName)){
                int countUnitName = unitBuildingService.selectCount(new EntityWrapper<UnitBuilding>().eq("community_id",unitBuilding.getCommunityId()).eq("unit_name",unitName.trim()));
                if(countUnitName>0){ return  R.error(400,"单元名称已存在");}
                upTag = true;
                upUnitNameTag= true;
                unitBuilding.setUnitName(unitName);
            }
        }
        if(StringUtils.isNotBlank(unitRemarks)){
            if(unitRemarks.length()>=200){return  R.error(400,"备注信息内容过长");}
            if(! unitBuilding.getUnitRemarks().equals(unitRemarks)){
                upTag = true;
                unitBuilding.setUnitRemarks(unitRemarks);
            }
        }
        if(null!=isShowApp){
            if(isShowApp!=2){isShowApp=1;}
            if(isShowApp!=unitBuilding.getIsShowApp()){
                upTag = true;unitBuilding.setIsShowApp(isShowApp);
            }
        }
        if(upTag){
            unitBuildingService.updateById(unitBuilding);
            if(upUnitNameTag){//单元名称修改
                //修改单元名称 同步修改 关联表单元名称
                unitBuildingService.updateJoinTableUnitName(unitBuilding.getUnitName(),unitBuilding.getCommunityId(),unitBuilding.getUnitId());
              //修改关联卡片的 单元名称
                unitBuildingService.updateCardJoinTableUnitName(unitBuilding.getUnitId());
            }
            // 同步清除 查询单元楼层户室的缓存
            unitBuildingService.clearPreKeyCache("unitHouse:selectUnitFloorHouse");
        }
        return R.ok();
    }

    @ApiOperation(value = "查询小区下级所有单元")
    @RequestMapping(value = "/readList",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="communityId",value="社区id",required = true,dataType = "long",paramType="form"),
    })
    public R readList(Long communityId) {
        parameterIsNull(communityId,"社区id不能为空");
        List<UnitBuilding> unitList = unitBuildingService.selectList(new EntityWrapper<UnitBuilding>().eq("community_id",communityId).orderBy("unit_id",true));
        if(null == unitList){unitList = new ArrayList<UnitBuilding>();}
        return R.ok().put("data",unitList).putDescription(UnitBuilding.class);
    }

    @ApiOperation(value = "批量创建单元下的楼层及户室")
    @RequestMapping(value = "/addFloorHouse",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="unitId",value="单元id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="addUnitFloorNum",value="单元添加的楼层数量(默认1)",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="addUnitFloorHouseNum",value="每层楼添加的户室数量(默认1)",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="propertyId",value="户室收费模板id",required = false,dataType = "long",paramType="form"),
    })
    public R addFloorHouse(Long unitId,Integer addUnitFloorNum,Integer addUnitFloorHouseNum,Long propertyId){
        parameterIsNull(unitId,"单元id不能为空");
        UnitBuilding unit = unitBuildingService.selectById(unitId);
        parameterIsNull(unit,"没有该单元信息");
        ChargeTemplate chargeTemplate = null;
        if(null!=propertyId){
            chargeTemplate=  chargeTemplateService.selectById(propertyId);
            if(null==chargeTemplate){return R.error(400,"没有该收费模板信息");}
        }
        if(null==addUnitFloorNum||addUnitFloorNum<1){addUnitFloorNum=1;}
        if(null==addUnitFloorHouseNum||addUnitFloorHouseNum<1){addUnitFloorHouseNum=1;}
        if(addUnitFloorHouseNum>99){ return R.error(400,"每层楼最多创建99个户室");}
        List<UnitFloor> floorList = new ArrayList<UnitFloor>();
        List<UnitHouse> houseList = new ArrayList<UnitHouse>();
        int floorCount =  unitFloorService.selectCount(new EntityWrapper<UnitFloor>().eq("unit_id",unit.getUnitId()));
        for(int x=1;x<=addUnitFloorNum;x++){
            UnitFloor addFloor = new UnitFloor();
            addFloor.setCommunityId(unit.getCommunityId());
            addFloor.setUnitId(unit.getUnitId());
            addFloor.setIsShowApp(1);
            addFloor.setFloorSort(floorCount+x);
            addFloor.setFloorName((floorCount+x)+"楼");
            addFloor.setAgencyId(unit.getAgencyId());
            for(int y=1;y<=addUnitFloorHouseNum;y++){
                UnitHouse addHouse = new UnitHouse();
                addHouse.setCommunityId(unit.getCommunityId());
                addHouse.setFloorId(addFloor.getFloorId());
                addHouse.setHouseRemarks("");
                addHouse.setIsShowApp(1);
                addHouse.setAgencyId(unit.getAgencyId());
                addHouse.setChargeTemplateId(propertyId);
                addHouse.setUnitName(unit.getUnitName());
                addHouse.setUnitId(unit.getUnitId());
                addHouse.setIsHaveMaster(2);//设置无会员认证
                addHouse.setIsHaveMember(2);//设置无户主信息
                addHouse.setHouseSort(y);
                addHouse.setFloorSort(addFloor.getFloorSort());
                addHouse.setIsEstateHouse(2);//设置不是物业办公室
                if(null == addHouse.getChargeTemplateId() ){
                    addHouse.setIsHavaChargeTemplate(2);//设置未配置物业费模板
                }
                if(null!=addHouse.getChargeTemplateId()){
                    addHouse.setIsHavaChargeTemplate(1);//设置已配置物业费模板
                    addHouse.setChargeTemplateName(chargeTemplate.getChargeTemplateName());
                }
                if(addHouse.getHouseSort()<10){
                    addHouse.setHouseNumber(addFloor.getFloorSort()+"0"+addHouse.getHouseSort());
                }
                if(addHouse.getHouseSort()>9){
                    addHouse.setHouseNumber(addFloor.getFloorSort()+""+addHouse.getHouseSort());
                }
                houseList.add(addHouse);
            }
            floorList.add(addFloor);
        }
        unitFloorService.insertBatch(floorList);
        unitHouseService.insertBatch(houseList);
        // 同步清除 查询单元楼层户室的缓存
        unitBuildingService.clearPreKeyCache("unitHouse:selectUnitFloorHouse");
        return R.ok();
    }

    @ApiOperation(value = "清除单元 里的所有楼层房屋信息")
    @RequestMapping(value = "/clearUnit",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="unitId",value="单元id",required = true,dataType = "Long",paramType="form"),
    })
    public R clearUnit_FloorAndHouse(Long unitId){
        parameterIsNull(unitId,"请选择单元");
        UnitBuilding unit = unitBuildingService.selectById(unitId);
        parameterIsNull(unit,"没有该单元信息");
        int countUnitTwoHouStateNum =unitHouseService.selectCount(new EntityWrapper<UnitHouse>().eq("unit_id",unitId).eq("is_have_member",2));
        if(countUnitTwoHouStateNum>0){return R.error(400,"该单元有户室已有会员认证,无法清除") ;}
        unitHouseService.delete(new EntityWrapper<UnitHouse>().eq("unit_id",unitId));
        houseMasterInfoService.delete(new EntityWrapper<HouseMasterInfo>().eq("unit_id",unitId));
        unitFloorService.delete(new EntityWrapper<UnitFloor>().eq("unit_id",unitId));
        // 同步清除 查询单元楼层户室的缓存
        unitBuildingService.clearPreKeyCache("unitHouse:selectUnitFloorHouse");
        return R.ok();
    }

    @ApiOperation(value = "单元批量绑定物业费模板(覆盖原来的)")
    @RequestMapping(value = "/bingChargeTemplateToHouseByUnitId",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="unitId",value="单元id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="chargeTemplateId",value="物业费模板id",required = true,dataType = "Long",paramType="form"),
    })
    public R bingChargeTemplateToHouseByUnitId(Long unitId,Long chargeTemplateId){
        parameterIsNull(unitId,"请选择单元");
        UnitBuilding unit = unitBuildingService.selectById(unitId);
        parameterIsNull(unit,"没有该单元信息");
        parameterIsNull(chargeTemplateId,"请选择物业费模板");
        ChargeTemplate chargeTemplate =chargeTemplateService.selectById(chargeTemplateId);
        parameterIsNull(chargeTemplate,"没有该物业费模板信息");
        List<UnitHouse> unitHouses = unitHouseService.selectList(new EntityWrapper<UnitHouse>().eq("unit_id",unitId));
        if(null!=unitHouses&&!unitHouses.isEmpty()){
            for(int x=0;x<unitHouses.size();x++){
                unitHouses.get(x).setChargeTemplateId(chargeTemplateId);
                unitHouses.get(x).setChargeTemplateName(chargeTemplate.getChargeTemplateName());
                unitHouses.get(x).setIsHavaChargeTemplate(1);
            }
            unitHouseService.updateBatchById(unitHouses);
        }
        return R.ok();
    }
}
